<template>
	<view>
		<view style="height: 300rpx"></view>
		<!-- 悬浮提交按钮 -->
		<view class="vp-foot">
		    <view style="background: #ffffff; padding: 20rpx">
		        <view class="deal" style="text-align: center">
		            <text :class="'is_deal '+(isDeal ? 'is_deal_on' : '')" @click="ondealChange">我已阅读并同意</text>
		            <navigator :url="cfg.page_xy">《用户协议》</navigator>
		            <text>和</text>
		            <navigator :url="cfg.page_fw">《服务协议》</navigator>
		        </view>
		        <view>
		            <button :class="'btnp ' + (isDeal ? '' : 'btnp-disabled')" @click="submit">
		                确认下单
		                <block v-if="curHospital.service_price > 0">（支付{{curHospital.service_price}}元）</block>
		            </button>
		        </view>
		    </view>
		</view>
		<uni-popup ref="popup" type="center" :is-mask-click="false" background-color="#fff" borderRadius="10px 10px">
		    <view class="popup-content">
		        <view class="group">
		            <input class="uni-input" type="tel" v-model="validMobile.phone" placeholder="手机号" />
		        </view>
		        <view class="group">
		            <input class="uni-input" v-model="validMobile.validCode" placeholder="验证码" />
		            <text
						class="valid-text"
						@click="countdownChange"
					>{{countdown.validText}}</text>
		        </view>
		    </view>
		    <view class="btns">
		        <view class="cancal" @click="cancel">取消</view>
		        <view class="ok" @click="ok">确定</view>
		    </view>
		</uni-popup>
		<!-- 付款二维码生成 -->
		<uni-popup ref="qrcodePopup" type="center" :is-mask-click="false" >
			<view class="pay-box">
				<img @click="payment" style="display: block;width: 30rpx;height: 30rpx;" src="/static/resource/images/modal_closer.png" />
				<view class="text-center">
					微信支付
				</view>
				<canvas id="qrcode" canvas-id="qrcode" style="width: 300rpx;height: 300rpx;"></canvas>
				<view class="text-center">
					请用本人微信扫描以上二维码
				</view>
			</view>
		</uni-popup>
		
		
	</view>
</template>

<script>
	import UQRCode from 'uqrcodejs'; 
	const app = getApp()
	let data = {}
	export default {
		props:["curHospital","service","formData"],
		data() {
			return {
				//账号登录的手机号，验证码
				validMobile:{
					phone:'',
					validCode:''
				},
				countdown:{
					validText:'获取验证码',
					time: 60
				},
				//用户协议、服务协议
				cfg:{
					page_xy:'',
					page_fw:''
				},
				//是否同意协议
				isDeal: false,
				//获取验证码的按钮是否可以点击
				flag:false
			}
		},
		methods: {
			//是否同意用户协议
			ondealChange(){
				this.isDeal = !this.isDeal
			},
		     validateData(title){
				uni.showToast({
					title,
					icon:'none',
					duration:1000
				})
			},
			async submit(){
			
				data.service_id = this.service.id
				data.service_code = this.service.code
				data.service_name = this.service.name
				data.service_stype = this.service.stype
				
				data.hospital_id = this.curHospital.id
				data.hospital_name = this.curHospital.name
				
				data.starttime = this.formData.starttime
				
				data.tel = this.formData.tel
				
				//陪诊服务
				if(this.service.stype === '10' || this.service.stype === '15' || this.service.stype === '20'){
					data.client = {...this.formData.client}
					data.receiveAddress = this.formData.receiveAddress
					if(data.starttime === ''){
						this.validateData('请选择就诊时间')
						return
					}
					
					// 使用 some 方法来验证收件信息
					const isAddressValid = Object.keys(data.client).some((item) => {
						  if (data.client[item] === '') {
							this.validateData('请选择就诊人')
							return true    // 找到一个空值，停止验证
						  }
						  return false  // 没有空值，继续验证
					})
					
					if (isAddressValid) return // 如果收件信息不完整，终止后续逻辑
					
					if(data.receiveAddress === ''){
						this.validateData('请填写就诊人所在地址')
						return
					}
					
					
					
				}else if(this.service.stype === '30' || this.service.stype === '40' ){
					//代跑服务
					data.address = {...this.formData.address}
				
					if(data.starttime === ''){
						this.validateData('请选择期望服务时间')
						return 
						
					}
					
					// 使用 some 方法来验证收件信息
					const isAddressValid = Object.keys(data.address).some((item) => {
						  if (data.address[item] === '') {
							this.validateData('请选择收件信息');
							return true  // 找到一个空值，停止验证
						  }
							return false  // 没有空值，继续验证
					});
					if (isAddressValid) return  // 如果收件信息不完整，终止后续逻辑
					
				}
				// 验证手机号码
				if (data.tel === '') {
				  this.validateData('请填写手机号码');
				  return;
				}
				
				console.log('data',data)
				
				
				//获取token，判断是否处于登录状态
				if(!uni.getStorageSync('token')){
					//未登录，打开弹框，用户进行登录
					this.$refs.popup.open('center')
				}else{
					//下单
					this.createOrder()
				}
				
			
			},
			// 点击获取验证码
			async countdownChange(){
				//验证手机号
				if(this.validMobile.phone === ''){
					this.validateData('手机号不能为空')
					return 
				}
				if(this.flag) return
				//倒计时开始时，按钮处于不可点击状态
				this.flag = true
				const timer = setInterval(()=>{
						if(this.countdown.time <= 0){
							this.countdown.validText = '获取验证码'
							this.countdown.time = 60
							clearInterval(timer)
							this.flag = false
							
						}else{
							this.countdown.time--
							this.countdown.validText = `剩余${this.countdown.time}秒`
						}
						
				},1000)
				//发送验证码
				
				await app.globalData.utils.request({
					url:'/get/code',
					data:{
						tel:this.validMobile.phone
					},
					method:'post'
				})
				
			},
			//关闭弹框
			cancel(){
				this.$refs.popup.close()
			},
			async ok(){
				//验证手机号
				if(this.validMobile.phone === ''){
					this.validateData('手机号不能为空')
					return 
				}else if(this.validMobile.validCode === ''){
					this.validateData('验证码不能为空')
					return 
				}
				//发起请求给后端，获取登录token
				const {data:{token}}  = await app.globalData.utils.request({
					url:'/user/authentication',
					method:'post',
					data:{
						tel:this.validMobile.phone,
						code:this.validMobile.validCode
					}
				})
				uni.setStorageSync('token',token)
				this.cancel()
				//下单
				this.createOrder()
			},
			//创建订单
			async createOrder(){
				const {wx_code} = await app.globalData.utils.request({
					url:'/pay/createOrder',
					method:'post',
					header:{
						token:uni.getStorageSync('token')
					},
					data
				})
				this.$refs.qrcodePopup.open('center')
				this.createQrcode(wx_code)
			},
			//创建二维码
			createQrcode(code) {
				  // 获取uQRCode实例
				  var qr = new UQRCode();
				  // 设置二维码内容
				  qr.data = code;
				  // 设置二维码大小，必须与canvas设置的宽高一致
				  qr.size = 150;
				  // 调用制作二维码方法
				  qr.make();
				  // 获取canvas上下文
				  var canvasContext = uni.createCanvasContext('qrcode', this); // 如果是组件，this必须传入
				  // 设置uQRCode实例的canvas上下文
				  qr.canvasContext = canvasContext;
				  // 调用绘制方法将二维码图案绘制到canvas上
				  qr.drawCanvas();
			},
			//跳转到订单列表
			payment(){
				app.globalData.orders_filt = '0'
				uni.switchTab({
					url:'/pages/order/index'
				})
			}
		}
	}
</script>

<style>
	
</style>
